package SocketLearn.NetSocketLearn;




import org.junit.jupiter.api.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author Lenl
 * @version v1.0
 * @create 2021-06-06 14:16
 * @description 实现TCP的网络编程
 * 例子1：客户端发送数据到服务端，服务端将数据打印在控制台
 *
 */
public class TCPTest1 {
    //客户端
    @Test
    public void client(){
        Socket socket= null;
        OutputStream os= null;
        try {
            InetAddress inet=InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet,8899);

            os = socket.getOutputStream();
            os.write("你好，我是客户端".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    //服务端
    @Test
    public void server(){
        ServerSocket socket=null;
        Socket s=null;
        InputStream is=null;
        ByteArrayOutputStream baos=null;
        try {
            //1.创建服务器端的ServerSocket，指明自己的端口号
            socket=new ServerSocket(8899);
            //2.调用accept()表示接收来自于客户端的socket
            s=socket.accept();
            //3.获取输入流
            //直接使用is.read()中文会有乱码
            is=s.getInputStream();
            //4.读取输入流中的数据
             baos=new ByteArrayOutputStream();
            byte[] buffer=new byte[5];
            int len;
            while((len=is.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());
            System.out.println("收到来自"+s.getInetAddress().getHostAddress()+"的数据");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(baos!=null)
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(is!=null)
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(s!=null)
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(socket!=null)
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}
